import { getSongUrl } from "@/service/music";

export default {
  namespaced: true,
  state() {
    return {
      currentIndex: -1,
      currentList: [],
      playerType: 'mini',
      playMode: 3,
    }
  },
  getters: {
    currentSong(state) {
      const { currentList, currentIndex } = state;
      if (!currentList.length) return;
      return currentList[currentIndex];
    },
  },
  mutations: {
    changeIndex(state, data) {
      state.currentIndex = data;
    },
    changeList(state, data) {
      state.currentList = data;
    },
    changeType(state, data) {
      state.playerType = data;
    },
    // changeMode(state) {
    //   state.playMode = state.playMode === 3 ? 1 : state.playMode + 1;
    // },
    changeMode(state, data) {
      state.playMode = data;
    },
  },
  actions: {
    async addMusic({ commit }, data) {
      const { list, idx } = data;
      const midList = list.map((item) => {
        return item.mid;
      });
      const res = await getSongUrl(midList);
      const { err, urls } = res || {};
      if (err) return;
      const newList = list.map((item, index) => {
        return {
          ...item,
          songUrl: urls[index],
        };
      });
      commit('changeList', newList);
      commit('changeIndex', idx);
      commit('changeType', 'full')
    },
    changeMusic({ commit, state }, data) {
      const { currentIndex, currentList }  = state;
      let idx = currentIndex;
      const maxIndex = currentList.length - 1;
      if (data === 'prev') {
        idx = idx <= 0 ? maxIndex : idx - 1;
      } else {
        idx = idx >= maxIndex ? 0 : idx + 1;
      }
      commit('changeIndex', idx);
    },
    changeMusicRandom({ commit, state }) {
      const randomIndex = Math.floor(Math.random() * state.currentList.length, 10);
      commit('changeIndex', randomIndex);
    },
  },
};